package com.mobile.check.dialogs;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Environment;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.kit.Kits;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import com.mobile.check.app.R;
import com.mobile.check.util.AppContents;
import com.mobile.check.util.DoubleUtil;


/**
 * Created by Administrator on 2017/4/18.
 */

public class CheckTipDialog extends Dialog implements DialogInterface.OnDismissListener {
    TextView receiveTv;
    TextView maxTv;
    TextView minStopTimeTv;
    LinearLayout minStopTimeLayout;
    private TextView submit_tv;
    //    Disposable disposable;
    Disposable timerDisposable;
    Disposable TestDisposable;
    SlectClickListener mSlectClickListener;
    int realMinStopTime;

    public CheckTipDialog(Context context, SlectClickListener listener) {
        super(context, R.style.WinDialog);
        mSlectClickListener = listener;
        setContentView(R.layout.dialog_checktip);
        init();
    }


    public void display(int minStopTime) {
        if (AppContents.ISTEST) {
            minStopTime=0;
        }
        Window dialogWindow = getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER_VERTICAL);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 0;//设置Dialog距离底部的距离
//       将属性设置给窗体
        dialogWindow.setAttributes(lp);
        show();//显示对话框

        setCanceledOnTouchOutside(false);
        setCancelable(false);
        if (minStopTime != 0) {
            minStopTimeTv.setText(String.valueOf(minStopTime));
            startTimer(minStopTime);
        } else {
            submit_tv.setBackgroundResource(R.drawable.shape_rect_3675bd);
            minStopTimeLayout.setVisibility(View.GONE);
        }
        if (AppContents.ISTEST) {
            final float[] testValue = new float[]{12.00f,11.00f,3000f,12.55f,2600f,18f,1000f,19.06f,20,21.78f,35,12,25,14};
            TestDisposable =  Observable.interval(1000, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
                @Override
                public void accept(Long aLong) throws Exception {
                    float receive =testValue[(Integer.parseInt(aLong.toString()))%testValue.length];
                    setReceiveDatas(receive);
                }
            });
        }

    }

    public void display() {
        display(0);
    }

    RecyclerView.OnScrollListener onScrollListener;


    private void init() {
        realMinStopTime = SharedPref.getInstance(getOwnerActivity()).getInt(AppContents.WAITTIME, 10);
        submit_tv = (TextView) findViewById(R.id.submit_tv);
        receiveTv = (TextView) findViewById(R.id.receiveTv);
        maxTv = (TextView) findViewById(R.id.maxTv);
        minStopTimeTv = (TextView) findViewById(R.id.minStopTimeTv);
        minStopTimeLayout = findViewById(R.id.minStopTimeLayout);
        submit_tv.setBackgroundColor(getContext().getResources().getColor(R.color.textgruy));
        setOnlistener();
    }

    private void setOnlistener() {
        submit_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String maxValue = maxTv.getText().toString();
                if (!TextUtils.isEmpty(maxValue)) {
                    try {
                        double value = DoubleUtil.getDouble(maxValue, 1);
                        if(value<0){
                            value = 0;
                        }
                        mSlectClickListener.submitClick(String.valueOf(value));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                dismiss();
            }
        });

    }

    public interface SlectClickListener {
        void submitClick(String value);
    }

    private void startTimer(final int minStopTime) {
        submit_tv.setClickable(false);
        if (timerDisposable != null) {
            timerDisposable.dispose();
        }
        timerDisposable = Observable.interval(0, 1, TimeUnit.SECONDS).take(minStopTime + 1).map(new Function<Long, Long>() {
            @Override
            public Long apply(Long aLong) throws Exception {
                return minStopTime - aLong;
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<Long>() {
            @Override
            public void accept(Long index) throws Exception {
                if (minStopTime - index >= realMinStopTime) {
                    submit_tv.setBackgroundResource(R.drawable.shape_rect_3675bd);
                    submit_tv.setClickable(true);
                }
                minStopTimeTv.setText(String.valueOf(index));
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {

            }
        }, new Action() {
            @Override
            public void run() throws Exception {
                submit_tv.setBackgroundResource(R.drawable.shape_rect_3675bd);
                submit_tv.setClickable(true);
            }
        });
    }


    String currentTime = Kits.Date.getYmdhmsS(Calendar.getInstance().getTimeInMillis());

    private void write(String content) {
        String fileName = "蓝牙RR" + currentTime + ".txt";
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String crashDir = Environment.getExternalStorageDirectory() + "/监测点系统日志/";
            Kits.File.writeFile(crashDir + fileName, "\n" + currentTime + ":" + content, true);
        }
    }


    private Float getMaxtValue() {
        String lastData = maxTv.getText().toString();
        if (TextUtils.isEmpty(lastData)) {
            return null;
        }
        Float lastValue = null;
        try {
            lastValue = Float.parseFloat(lastData);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return lastValue;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (TestDisposable !=null && !TestDisposable.isDisposed()) {
            TestDisposable.dispose();
        }
//        disposable.dispose();
    }


    public void setReceiveDatas(float receiveData) {
//        if(receiveData<0){
//            receiveData = 0;
//        }
        receiveTv.setText(String.valueOf(receiveData));
        Float maxtValue = getMaxtValue();
        if (null == maxtValue || maxtValue < receiveData) {
            maxTv.setText(String.valueOf(receiveData));
        }
    }


}
